//
// Created by Administrator on 2021/8/17.
//

#include "udpServer.h"


const quint16 PORT = 2333;

udpServer::udpServer(QObject *p) : QObject(p), udpSocket(new QUdpSocket), w(nullptr) {
    udpSocket->bind(QHostAddress("0.0.0.0"), PORT);
    connect(udpSocket, SIGNAL(readyRead()), this, SLOT(receive()));
}

udpServer::~udpServer() {
    delete udpSocket;
}

void udpServer::receive() {
    QByteArray ba;
    while (udpSocket->hasPendingDatagrams()) {
        ba.resize(udpSocket->pendingDatagramSize());
        QHostAddress sendAddr;
        udpSocket->readDatagram(ba.data(), ba.size(), &sendAddr);

//        QString value = QString::fromLocal8Bit(ba);
        Msg *revMsg = (Msg *)(ba.data());
        qDebug() << revMsg->msg;
        QString msg = QString::fromUtf8(revMsg->msg);
        w->addTableItem(revMsg->level, sendAddr.toString(),  msg);
        if (sendAddr.toString() == "10.30.30.200") {
            // model->setItem(row, 2, new QStandardItem(QString::fromLocal8Bit("Prod")));
            msg.insert(0, QString::fromUtf8("正式环境 \n"));
        } else {
            // model->setItem(row, 2, new QStandardItem(QString::fromLocal8Bit("Test")));
            msg.insert(0, QString::fromLocal8Bit("测试环境 \n"));
        }
        w->showMessage(revMsg->level, msg);
    }
}
